//
//  Contacts.swift
//  ADKit
//
//  Created by Adoma on 2020/10/30.
//

import Contacts

public struct Contact {
    
    var id: String
    public var prefix: String
    public var name: String
    public var phone: String
    public var avatar: UIImage?
}

public struct ContactsManager {
    
    public static func getContacts() -> [Contact] {
        
        var contacts: [Contact] = []
        
        var temp: [String: Bool] = [:]
        
        let keys = [CNContactIdentifierKey, CNContactNamePrefixKey, CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey] as [CNKeyDescriptor]
        
        let request = CNContactFetchRequest.init(keysToFetch: keys)
        
        do {
            try Authorize.shared.contactStore.enumerateContacts(with: request) { c, _ in
                
                for number in c.phoneNumbers {
                    
                    let phone = number.value.stringValue.replacingOccurrences(of: " ", with: "")
                    let prefix = c.namePrefix
                    let name = c.familyName + c.givenName
                    
                    if temp[phone] == true {
                        continue
                    }
                    
                    var contact = Contact.init(id: number.identifier, prefix: prefix, name: name, phone: phone)
                    if let data = c.imageData {
                        contact.avatar = UIImage.init(data: data)
                    }
                    contacts.append(contact)
                    
                    temp[phone] = true
                }
                
            }
        } catch {
            ADToast.show(msg: error.localizedDescription)
        }
        return contacts
    }
}
